import actionTypes from "../action-types"
import {reqLogin, reqLogout, reqVerifyAuthToken} from "../../api/login"
import {setToken} from "../../request/auth";

const startLogin = () => {

    return {
        type: actionTypes.START_LOGIN,
        isLoading: false,
    }
};

const loginSuccess = (userInfo, token) => {
    return {
        type: actionTypes.LOGIN_SUCCESS,
        payload: {userInfo},
        token: token,
        isLoading: false,
        isLogin: true,
    }
};

const loginFailed = () => {

    window.localStorage.removeItem("authToken");
    window.localStorage.removeItem("userInfo");

    return {
        type: actionTypes.LOGIN_FAILED,
    }
};

/*登录*/
export const login = (data) => (dispatch) => {
    return new Promise((resolve, reject) => {
        dispatch(startLogin());
        reqLogin(data).then((response) => {
            if (response.code === 200) {
                dispatch(loginSuccess(response.data, response.data.token));
                console.log(response);
                setToken(response.data.token);
                window.localStorage.setItem("authToken", response.data.token);
                window.localStorage.setItem("userInfo", JSON.stringify(response.data.rows));
                // window.sessionStorage.setItem("authToken", "");
                // window.sessionStorage.setItem("userInfo", "");
                resolve(response);
            } else {
                dispatch(loginFailed());
            }
        }).catch((error) => {
            reject(error);
        })
    })
};

/*退出*/
export const logout = (data) => {
    return dispatch => {
        dispatch(startLogin());
        reqLogout(data).then(response => {
            if (response.code === 200) {
                dispatch(loginFailed())
            } else {
                dispatch(loginFailed())
            }
        });
    }
};



